//sql.js文件：
module.exports = {
  insert({ colName, data }) {
    //colName:集合名称  //data要插入的数据
    return new Promise((resolve, reject) => {
      colName.insertMany(data, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve("插入成功");
        }
      });
    });
  },

  update({ colName, where = {}, data, num = 1 }) {
    //如果传入的是num=1则只修改一条 where：条件
    const type = num === 1 ? "updateOne" : "updateMany";
    return new Promise((resolve, reject) => {
      colName[type](where, data, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve("修改成功");
        }
      });
    });
  },

  delete({ colName, where = {}, num = 1 }) {
    const type = num === 1 ? "deleteOne" : "deleteMany";
    return new Promise((resolve, reject) => {
      colName[type](where, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve("删除成功");
        }
      });
    });
  },

  //根据指定条件查询
  get({ colName, where = {} }) {
    return new Promise((resolve, reject) => {
      colName.find(where, { _id: 0, __v: 0 }, (err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data); //把查询数据返回
        }
      });
    });
  },

  //分页查询
  getPage({ colName, where = {}, index = 0, num = 2 }) {
    return new Promise((resolve, reject) => {
      colName
        .find(where, { _id: 0, __v: 0 })
        .limit(num)
        .skip(num * index)
        .exec((err, data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data); //把查询数据返回
          }
        });
    });
  },

  //排序查询
  getSort({ colName, where = {}, sort = {} }) {
    return new Promise((resolve, reject) => {
      colName
        .find(where, { _id: 0, __v: 0 })
        .sort(sort)
        .exec((err, data) => {
          if (err) {
            reject(err);
          } else {
            resolve(data); //把查询数据返回
          }
        });
    });
  },

  //查询类别
  getMold({ colName, keyword }) {
    return new Promise((resolve, reject) => {
      colName.distinct(keyword).exec((err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data); //把查询数据返回
        }
      });
    });
  },

  //查询数量
  getLen({ colName }) {
    return new Promise((resolve, reject) => {
      colName.countDocuments().exec((err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data); //把查询数据返回
        }
      });
    });
  },
};
